
import {
    Injectable
} from '@angular/core';
import { Cookie } from './cookie';

@Injectable()
export class HttpCacheService {
    localStorageTest() {
        const test = 'test';
        try {
            localStorage.setItem(test, test);
            localStorage.getItem(test);
            localStorage.removeItem(test);
            return true;
        } catch (e) {
            console.log('浏览器缓存已被禁用!');
            return false;
        }
    }
    saveLocalCache(key: string, value: string) {
        const storage = (this.localStorageTest() ? window.localStorage : false);
        storage ? storage.setItem(key, value) : Cookie.set(key, value);
    }
    removeLocalCache(key: string) {
        const storage = (this.localStorageTest() ? window.localStorage : false);
        storage ? storage.removeItem(key) : Cookie.delete(key);
    }
    getLocalCache(key: string): string {
        let strValue = '';
        const storage = (this.localStorageTest() ? window.localStorage : false);
        storage ? (storage.getItem(key) != null ? strValue = storage.getItem(key) : strValue = Cookie.get(key)) : null;
        return strValue;
    }



	sessionStorageTest() {
        const test = 'test';
        try {
            sessionStorage.setItem(test, test);
            sessionStorage.getItem(test);
            sessionStorage.removeItem(test);
            return true;
        } catch (e) {
            console.log('浏览器缓存已被禁用!');
            return false;
        }
    }
    saveSessionCache(key: string, value: string) {
        const storage = (this.sessionStorageTest() ? window.sessionStorage : false);
        storage ? storage.setItem(key, value) : Cookie.set(key, value);
    }
    removeSessionCache(key: string) {
        const storage = (this.sessionStorageTest() ? window.sessionStorage : false);
        storage ? storage.removeItem(key) : Cookie.delete(key);
    }
    getSessionCache(key: string): string {
        let strValue = '';
        const storage = (this.sessionStorageTest() ? window.sessionStorage : false);
        storage ? (storage.getItem(key) != null ? strValue = storage.getItem(key) : strValue = Cookie.get(key)) : null;
        return strValue;
    }
}

